package io.kimmking.rpcfx.demo.provider;

import io.kimmking.rpcfx.server.NettyHttpServer;
import io.kimmking.rpcfx.server.RpcfxInvoker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@SpringBootApplication
@RestController
public class RpcfxServerApplication {



	public static void main(String[] args) throws Exception {
		// 在spring加载完成后，从里面拿到特定注解的bean，自动注册到zk
		ConfigurableApplicationContext ctx = new SpringApplicationBuilder()
				.sources(RpcfxServerApplication.class).web(false).run(args);
		RpcfxInvoker invoker = ctx.getBean(RpcfxInvoker.class);
		//startWithZk(ctx, invoker);
		startWithRedis(ctx,invoker);
	}

	/**
	 * 用redis注册中心启动
	 * @param ctx
	 * @param invoker
	 * @throws Exception
	 */
	private static void startWithRedis(ConfigurableApplicationContext ctx, RpcfxInvoker invoker) throws Exception {
		//启动服务
		NettyHttpServer server = new NettyHttpServer();
		log.info("netty tcp start");
		String redisHost = "127.0.0.1";
		int redisPort = 6379;
		String namespace = "rpcfx";
		String cfgNamespace = "rpcfx_config";
		String metadataNamespace = "rpcfx_metadata";
		server.startWithRedisRegister(9000,invoker,ctx,redisHost,redisPort,namespace,cfgNamespace,metadataNamespace);
		System.out.println("netty tcp exit");
	}

	/**
	 * 用zk注册中心启动
	 * @param ctx
	 * @param invoker
	 * @throws Exception
	 */
	private static void startWithZk(ConfigurableApplicationContext ctx, RpcfxInvoker invoker) throws Exception {
		//启动服务
		NettyHttpServer server = new NettyHttpServer();
		log.info("netty tcp start");
		String zkServer = "127.0.0.1:2181";
		String namespace = "rpcfx";
		String cfgNamespace = "rpcfx_config";
		String metadataNamespace = "rpcfx_metadata";
		server.startWithZkRegister(9000,invoker,ctx,zkServer,namespace,cfgNamespace,metadataNamespace);
		System.out.println("netty tcp exit");
	}

	//	@PostMapping("/")
	//	public RpcfxResponse invoke(@RequestBody RpcfxRequest request) throws ClassNotFoundException {
	//		return invoker.invoke(request);
	//	}

	@Bean
	public RpcfxInvoker createInvoker(ApplicationContext applicationContext){
		return new RpcfxInvoker(applicationContext);
	}



}
